package com.happy3w.java.ext;

import java.io.File;
import java.util.Arrays;
import java.util.Spliterators;
import java.util.Stack;
import java.util.function.Consumer;

public class EnumerateFileSpliterator extends Spliterators.AbstractSpliterator<File> {
    private final Stack<File> fileStack = new Stack<>();
    private final EnumFileOption option;

    public EnumerateFileSpliterator(File file) {
        this(file, EnumFileOption.DEFAULT);
    }

    public EnumerateFileSpliterator(File file, EnumFileOption option) {
        super(0, 0);
        fileStack.push(file);
        this.option = option;
    }


    @Override
    public boolean tryAdvance(Consumer<? super File> action) {
        while (!fileStack.isEmpty()) {
            File file = fileStack.pop();
            if (option.isAcceptFile() && file.isFile()) {
                action.accept(file);
                return true;
            }
            if (file.isDirectory()) {
                File[] files = file.listFiles();
                if (files != null) {
                    if (option.getFileComparator() != null && files.length > 1) {
                        Arrays.sort(files, option.getFileComparator());
                    }
                    for (int i = files.length - 1; i >= 0; i--) {
                        fileStack.push(files[i]);
                    }
                }
                if (option.isAcceptDir()) {
                    action.accept(file);
                    return true;
                }
            }
        }
        return false;
    }
}
